//
//  NSString+GSSAdditions.m
//  iGSS
//
//  Copyright 2010 Electronic Business Systems Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "NSString+GSSAdditions.h"

#include <CommonCrypto/CommonHMAC.h>

@implementation NSString (GSSAdditions)

- (NSString *)stringByAppendingSlash {
    if ([self hasPrefix:@"/"])
        return self;
    return [self stringByAppendingString:@"/"];
}

- (NSString *)stringByAppendingURIComponent:(NSString *)aString {
    return [self stringByAppendingString:
            [aString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}

- (NSString *)stringByDeletingLastURIComponent {
    if (![self length])
        return self;
    
    NSRange range = [self rangeOfString:@"/"
                               options:NSBackwardsSearch
                                 range:NSMakeRange(0, [self length] - 1)];
    NSUInteger location = range.location;
    if (location == NSNotFound)
        return self;
    
	return [[self substringToIndex:location] stringByAppendingString:@"/"];    
}

- (NSString *)stringByDeletingURIQuery {
    NSRange range = [self rangeOfString:@"?"];
    if (range.location == NSNotFound)
        return self;
    else
        return [self substringToIndex:range.location];    
}

- (NSString *)stringByStrippingHTMLTags {
    BOOL inTag = NO;
    NSUInteger length = [self length];
    NSMutableString *m = [[NSMutableString alloc] initWithCapacity:length];
    
    for (int i = 0; i < length; i++) {
        unichar c = [self characterAtIndex:i];
        if (inTag) {
            if (c == '>')
                inTag = NO;
        } else {
            if (c == '<')
                inTag = YES;
            else
                [m appendFormat:@"%C", c];
        }
    }
    
    NSString *ret = [NSString stringWithString:m];
    [m release];
    return ret;
}

- (NSString *)SHA1Hash {
    unsigned char md[20];
	char mdhex[41];
	
	CC_SHA1([self UTF8String], [self length], md);
	for (int i = 0; i < 20; i++)
		sprintf(mdhex + i * 2, "%02x", md[i]);
	mdhex[40] = 0;
	
	return [NSString stringWithCString:mdhex encoding:NSASCIIStringEncoding];    
}

@end
